<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Request;
use App\Models\TeachesContentPpt;
use App\Models\TeachesCompanyPpt;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
use App\Models\TeachesContentVideo;
use App\Models\TeachesContentOffice;
use App\Models\TeachesCompanyOffice;
use App\Models\TeachesCompanyVideo;
use App\Models\Attachment;
use Intervention\Image\Facades\Image;
use YuanChao\Editor\EndaEditor;
use App\Models\CompanyPhoto;
/**
 *
 * @author Joker
 *        
 */
class UploadController extends Controller
{
    protected $uid;
    public function __construct()
    {
        $this->middleware('auth');
        $this->uid = Auth::user()->id;
    }


    /**
     * 企业图片
     */
    public function compImages()
    {
        $file = Request::file('upfile');
        $cid = Request::input('company_id');
        $base_dir = public_path();
        $filePath = "/uploads/images/company/".date("Ymd")."/";
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $mimeTye = $file->getMimeType();
            $newName = md5(date('ymdhis').$clientName).".".$extension;
            $file->move($base_dir.$filePath,$newName);

            $photo = new CompanyPhoto();
            $photo->company_id = $cid;
            $photo->name = $newName;
            $photo->path = $filePath.$newName;
            $photo->extension = $mimeTye;
            $photo->user_id = $this->uid;
            $photo->save();

            return Response::json(array('attach'=>$photo->path,'attach_id'=>$photo->image_id,'status'=>'success','msg'=>'上传图片成功！'));
        }
        else
        {
            return Response::json(array('url'=>'','status'=>'false','msg'=>'上传图片失败！'));
        }
    }


    /**
     * 
     */
    public function newsImages()
    {
        $file = Request::file('file');
        $base_dir = public_path();
        $dest_dir = Request::input('dest_dir');
        $is_attach = Request::input('attachment');
        if(empty($dest_dir) && $dest_dir != 'undefined')
        {
            $dest_dir = 'employ';
        }
        $filePath = "/uploads/images/".$dest_dir."/".date("Ymd")."/";
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $mimeType = $file->getMimeType();
            $newName = md5(date('ymdhis').$clientName).".".$extension;
    
            $file->move($base_dir.$filePath,$newName);
            $info = array(
                'name' => $clientName,
                'ext' => $extension,
                'filename' => $filePath.$newName,
                'attachment' => $filePath.$newName,
                'url' => $filePath.$newName,
                'filesize' => $file->getClientSize(),
            );
            if($is_attach)
            {
                $attach = new Attachment();
                
                $attach->app = $dest_dir;
                $attach->att_name = $newName;
                $attach->url = $filePath.$newName;
                $attach->type = $mimeType;
                $attach->save();
                $info['attachment_id'] = $attach->aid;
            }
            
            return Response::json($info);
        }
    }
    
    /**
     * 用户上传头像
     */
    public function userLogo()
    {
        $act = Request::input('type','');
        $userPath = md5($this->uid);
        $logoPath = substr($userPath,0,5).'/'.substr($userPath, 5,10).'/'.substr($userPath, 10).'/';
        $logo = '/uploads/avatar/'.$logoPath;
        if($act == 'up'){
            $file = Request::file('upfile');
            
            if($file->isValid()){
                $extension = $file->getClientOriginalExtension();
                $newfileName = 'original.'.$extension;
                $file->move(public_path($logo),$newfileName);
                $originalPath = public_path($logo.$newfileName);
                Image::make($originalPath);
                return Response::json(array('attach'=>$logo.$newfileName,'newurl'=>$logo.$newfileName."?v=".time(),'status'=>'success','msg'=>'上传用户头像成功！'));
            }else{
                return Response::json(array('status'=>'fail','msg'=>'上传用户头像失败！'));
            }
        }else{

            $pic = Request::input('img');
            $x = Request::input('x');
            $y = Request::input('y');
            $w = Request::input('w');
            $h = Request::input('h');
            $originalPath = public_path($pic);
            $extension = pathinfo($originalPath, PATHINFO_EXTENSION);
            $bigName = 'big.png';
            $middleName = 'middle.png';
            $smallName = 'small.png';
            $bigPath = public_path($logo.$bigName);
            $middlePath = public_path($logo.$middleName);
            $smallPath = public_path($logo.$smallName);
//             $attach = $this->sliceBanner($x,$y,$w,$h,$pic);
            
            $img = Image::make($originalPath);
            $img->crop( intval($w), intval($h),intval($x), intval($y));
            $img->fit(200);
            $img->save($bigPath);
            $img->fit(120);
            $img->save($middlePath);
            $img->fit(80);
            $img->save($smallPath);

            unlink($originalPath);
            return Response::json(array('attach'=>$pic,'status'=>'success','msg'=>'上传用户头像成功！'));

      }
    }

    /**
     * 青苜社区 图片上传
     */
    public function bbsImg()
    {
        $path = 'uploads/bbs/images/'.date('Ymd');
        $data = EndaEditor::uploadImgFile($path);
        return Response::json($data);
    }
    
    /**
     * PPT 教程上传  zip格式文件
     * 需要解压缩
     */
    public function teaches()
    {
        $file = Request::file('file');
        $app = Request::input('app');
        $base_dir = "/uploads/";
        $type='';
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
    
            $extension = $file->getClientOriginalExtension();
    
            $mimeType = $file->getMimeType();
    
            $newName = md5(date('ymdhis').$clientName);
    
            $newfileName = $newName.".".$extension;
            
            if($app == 'teaches_content')
            {
                $app='teaches';
                switch ($extension)
                {
                    case 'zip':
                        $video = new TeachesContentPpt();
                        $type = 'ppt';
                        break;
                    case 'mp4':
                        $video = new TeachesContentVideo();
                        $type = 'video';
                        break;
                    default:
                        $video = new TeachesContentOffice();
                        $type = 'office';
                        
                }
            }
            elseif($app == 'teaches_company')
            {
                $app='company';
                switch ($extension)
                {
                    case 'zip':
                        $video = new TeachesCompanyPpt();
                        $type = 'ppt';
                        break;
                    case 'mp4':
                        $video = new TeachesCompanyVideo();
                        $type = 'video';
                        break;
                    default:
                        $video = new TeachesCompanyOffice();
                        $type = 'office';
                
                }
            }
            else
            {
                
            }
            $filePath = $base_dir.$type."/".$app."/".date("Ymd")."/";
            $file->move(public_path($filePath),$newfileName);
            if($extension == 'zip')
            {
                 return $this->toArchive($file, $video, $filePath, $newfileName, $newName, $mimeType);
            }
            elseif($extension == 'mp4')
            {
                return $this->toVideo($file, $video, $filePath, $newfileName, $mimeType);
            }
            else
            {
                return $this->toOffice($file, $video, $filePath, $newName, $newfileName, $mimeType);
            }
    
        }
        else
        {
            return Response::json(array('success'=>false));
        }
    }
    
    
    /**
     * @param  $file
     * @param  $video
     * @param  $filePath
     * @param  $newName
     * @param  $newfileName
     * @param  $mimeType
     */
    private function toOffice($file,$video,$filePath,$newName,$newfileName,$mimeType)
    {
        $swf = office2swf($filePath.$newfileName, $newName, $filePath);
        if(empty($swf))
        {
            return Response::json(array('success'=>false,'msg'=>'转化格式失败！'));
        }
        elseif(empty($swf['pdfurl']) || empty($swf['swfurl']))
        {
            return Response::json(array('success'=>false,'msg'=>'转化格式失败！'));
        }
        $video->url = $filePath.$newfileName;
        $video->file_name = $newName;
        $video->size = $file->getClientSize();
        $video->file_path = $filePath;
        $video->type = $mimeType;
        $video->user_id = Auth::user()->id;
        $video->pdf_url = $swf['pdfurl'];
        $video->swf_url = $swf['swfurl'];
        if($video->save())
            return Response::json(array('url'=>$video->url,'id'=>$video->id,'success'=>true,'type'=>'office'));
        else
            return Response::json(array('success'=>false));
    }
    
    /**
     * @param  $file
     * @param  $video
     * @param  $filePath
     * @param  $newfileName
     * @param  $mimeType
     */
    private function toVideo($file,$video,$filePath,$newfileName,$mimeType)
    {
        $video->url = $filePath.$newfileName;
        $video->type = $mimeType;
        $video->size = $file->getClientSize();
        $video->user_id = $this->uid;
        
        if($video->save())
            return Response::json(array('url'=>$video->url,'id'=>$video->id,'success'=>true,'type'=>'video'));
        else
            return Response::json(array('success'=>false));
    }
    
    /**
     * @param file $file   上传的文件集合
     * @param collect $video 实例化对象
     * @param string $filePath 文件路径
     * @param string $newfileName 文件夹名称
     * @param string $newName 文件名称
     */
    private function toArchive($file,$video,$filePath,$newfileName,$newName,$mimeType)
    {
        $zip = new \ZipArchive();
        if($zip->open(public_path($filePath.$newfileName)) === TRUE)
        {
            $index=$zip->locateName('index.html', \ZipArchive::FL_NOCASE);
//             $contents = $zip->getFromIndex($index);
            if($index)
            {
                $zip->extractTo(public_path($filePath.$newName));//假设解压缩到在当前路径下images文件夹的子文件夹php
                $zip->close();//关闭处理的zip文件
                unlink(public_path($filePath.$newfileName));
                $video->url = $filePath.$newName."/index.html";
                $video->file_name = $newName;
                $video->size = $file->getClientSize();
                $video->file_path = $filePath;
                $video->type = $mimeType;
                $video->user_id = $this->uid;
                $video->save();
                return Response::json(array('url'=>$video->url,'id'=>$video->id,'success'=>true,'type'=>'ppt'));
            }
            else 
            {
                unlink(public_path($filePath.$newfileName));
                return Response::json(array('status'=>false,'msg'=>'压缩包请必须包含index.html！'));
            }
        
        }
        else
        {
            return Response::json(array('success'=>false));
        }
    }
}